package com.zjdiepu.www.biz.partner;

import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.base.core.BaseService;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.status.ThirdHandleStatus;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.base.enums.type.ThirdModeIDType;
import com.zjdiepu.www.dao.partner.ThHandleErrMapper;
import com.zjdiepu.www.ibiz.partner.IThHandleErrService;
import com.zjdiepu.www.ibiz.system.IBaseSysParamsService;
import com.zjdiepu.www.model.partner.dto.ThHandleErr;
import com.zjdiepu.www.model.partner.ext.ThHandleErrExt;
import com.zjdiepu.www.security.exception.BasePartnerException;
import com.zjdiepu.www.util.ExceptionHelper;

/**
 * Service层操作实现<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年09月21日 10时04分<br/>
 * @since 1.0<br/>
 */
@Service
public class ThHandleErrServiceImpl extends BaseService implements IThHandleErrService {
	public static final Logger logger = LoggerFactory.getLogger(ThHandleErrServiceImpl.class);
	
	@Resource
	private IBaseSysParamsService baseSysParamsService;
	@Autowired
	private ThHandleErrMapper thHandleErrMapper;

	@Override
	public ThHandleErr saveOrUpdateThHandleErr(Exception e, String busiId, String dataId,
			String thLogId, String thLogSubId, String busiType, String xeApplyNo,
			ThirdHandleStatus thirdHandleStatus,Integer intervalRetryCount,
			ThirdModeIDType ThModeIDType, String currentUserId,
			String currentUserName, Date now) {
		ThHandleErr thHandleErrParam = new ThHandleErr();
		thHandleErrParam.setDpStatus(DpStatus.NORMAL.getCode());
		thHandleErrParam.setBusiId(busiId);
		if(null == ThModeIDType) {
			// 不可能为null，为null时必定参数传错，调试阶段必须发现
			ExceptionHelper.thow("9999", "保存错误处理时参数模块ID为空");
		}
		thHandleErrParam.setThirdModeId(ThModeIDType.getCode());
		ThHandleErr thHandleErr = thHandleErrMapper.selectRefined(thHandleErrParam);
		boolean insert = false;
		if(null == thHandleErr) {
			insert = true;
			thHandleErr = new ThHandleErr();
			thHandleErr.initInsertData(currentUserId, currentUserName);
		} else {
			thHandleErr.initUpdateData(currentUserId, currentUserName);
		}
		String errorMsg = null;
		if(e != null && e instanceof BasePartnerException){
			errorMsg = ((BasePartnerException)e).getErrorMsg();
		} else if(e != null && e instanceof BaseException){
			errorMsg = ((BaseException)e).getErrorMsg();
		} else if(e != null) {
			if(null != e.getCause()) {
				errorMsg = e.getCause().toString();
			} else {
				errorMsg = "不可用预料的异常";
			}
		}
		
		thHandleErr.setDataId(dataId);
		thHandleErr.setBusiType(busiType);
		thHandleErr.setBusiId(busiId);
		thHandleErr.setThirdId(xeApplyNo);
		thHandleErr.setThirdModeId(ThModeIDType.getCode());
		thHandleErr.setThirdModeName(ThModeIDType.getValue());
		thHandleErr.setThLogId(thLogId);
		thHandleErr.setThLogSubId(thLogSubId);
		if (null != thirdHandleStatus) {
			thHandleErr.setThirdHandleStatus(thirdHandleStatus.getCode());
			thHandleErr.setThirdHandleStatusName(thirdHandleStatus.getValue());
			if (thirdHandleStatus == ThirdHandleStatus.CHU_LI_CHENG_GONG) {
				thHandleErr.setIsFinish(1);
			} else {
				thHandleErr.setIsFinish(0);
			}
		}
		thHandleErr.setErrInfo(errorMsg);
		thHandleErr.setTimeNext(intervalRetryCount == null ? null : new Date(now.getTime() + intervalRetryCount * 1000)); //没有配置系统参数时，重试时间为null，即永不执行
		Integer countRetry = thHandleErr.getCountRetry();
		thHandleErr.setCountRetry(countRetry == null ? 0 : (countRetry + 1));

		if(insert) {
			thHandleErrMapper.insert(thHandleErr);
		} else {
			thHandleErrMapper.updateByPrimaryKeySelective(thHandleErr);
		}
		return thHandleErr;
	}
	
	@Override
	public void saveUpdateAndDelete(ThHandleErr thHandleErr, OperateType operType) {
		switch (operType) {
		case add:
			thHandleErr.initInsertData(thHandleErr.getModifier(), thHandleErr.getModifierName());
			thHandleErrMapper.insert(thHandleErr);
			break;
		case edit:
			thHandleErr.initUpdateData(thHandleErr.getModifier(), thHandleErr.getModifierName());
			// 影响的记录数
			int updateCount = thHandleErrMapper.updateByPrimaryKeySelective(thHandleErr);
			if(updateCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(updateCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		case delete:
			thHandleErr.initDeleteData(thHandleErr.getModifier(), thHandleErr.getModifierName());
			// 影响的记录数
			int deleteCount = thHandleErrMapper.updateByPrimaryKeySelective(thHandleErr);
			if(deleteCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(deleteCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		default:
			break;
		}
	}
	
	@Override
	public List<ThHandleErr> selectByExt(ThHandleErrExt thHandleErrExt) {
		return thHandleErrMapper.selectByExt(thHandleErrExt);
	}
	
	@Override
	public int countByExt(ThHandleErrExt thHandleErrExt){
		return thHandleErrMapper.countByExt(thHandleErrExt);
	}
	
	@Override
	public ThHandleErr selectById(String id) {
		return thHandleErrMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public void clearEmpty(Set<String> fieldNames, String id) {
		if(CollectionUtils.isNotEmpty(fieldNames)){
			thHandleErrMapper.clearEmpty(fieldNames, id);
		}
	}
	
	@Override
	public int countRefined(ThHandleErr thHandleErr) {
		return thHandleErrMapper.countRefined(thHandleErr);
	}

	@Override
	public ThHandleErr selectRefined(ThHandleErr thHandleErr) {
		return thHandleErrMapper.selectRefined(thHandleErr);
	}
	
	@Override
	public int deletedRefined(ThHandleErr thHandleErr) {
		return thHandleErrMapper.deletedRefined(thHandleErr);
	}

	@Override
	public boolean repeat(ThHandleErr thHandleErr) {
		int count = countRefined(thHandleErr);
		if(count > 1) {
			return true;
		}
		if(count == 0) {
			return false;
		}
		
		if(StringUtils.isBlank(thHandleErr.getId())) {
			return true;
		}
		ThHandleErr dbItem = selectRefined(thHandleErr);
		if(null == dbItem) {
			return false;
		}
		return !thHandleErr.getId().equals(dbItem.getId());
	}
	
	@Override
	public int updateBatch(String modifier, String modifierName, Integer dpStatus, List<String> ids) {
		Integer current = (int)(System.currentTimeMillis() / 1000);
		return thHandleErrMapper.updateBatch(modifier, modifierName, current, dpStatus, ids);
	}
	
	@Override
	public int insertBatch(List<ThHandleErr> thHandleErrs) {
		return thHandleErrMapper.insertBatch(thHandleErrs);
	}
}
